//
//  TitlesSettingVC.m
//  GcwSDKDemo
//
//  Created by 陈超 on 2016/12/30.
//  Copyright © 2016年 陈超. All rights reserved.
//

#import "TitlesSettingVC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "VideoEffectUtil.h"
#import "VideoPlayBackVC.h"
#import "AppDelegate.h"
#import "VideoCoverPicker.h"
#import "UIUtils.h"
#import "FontModel.h"
@implementation TitlesSettingVC
-(void)viewDidLoad{
    [super viewDidLoad];
    self.animationImage=[AnimationImage new];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
        AppDelegate *delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    if(delegate.tmpVideoFrame!=NULL){//选取了一张视频截图
        [self.coverBgImage setImage:delegate.tmpVideoFrame];
    }
}
- (IBAction)onTextChanged:(UITextField *)sender {
    self.titlesLabel.text=[NSString stringWithFormat:@"表演者：%@",sender.text];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
- (IBAction)onClickIgnoreButton:(UIButton *)sender {

    if(self.delegate&&[self.delegate respondsToSelector:@selector(captruedTitlesView:)]){
        [self.delegate performSelector:@selector(captruedTitlesView:) withObject:nil];
    }

}

- (IBAction)onClickCompleteButton:(id)sender {

    __weak typeof(self) weakSelf=self;
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.inputUrl path]]){
        //如果还没有拍摄视频就返回
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    //设置含特效的视频路径
    [VideoEffectUtil sharedInstance].outPutVideoUrl=[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:
                                                                            @"myVideo.mp4"]];
    //待添加特效的视频路径
    NSURL *inPutVideoUrl=self.inputUrl;
    //titlesModel是指添加的片头图片和片头图片出现在视频中的时长

    [self saveThisCover];
    AppDelegate *delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    //设置比特率
    [VideoEffectUtil sharedInstance].bitRate=800000;
    //生成含特效的视频
    //inPutVideoUrl :想要加特效的源视频url
    //mp3Url: 本地背景音乐url，为nil时表示不加,录制了现场的声音时，建议不加
    //borderModel:遮罩的数据模型
    //tranformModel:图像变换的模型,这里可以控制视频的镜像翻转,分身数(一分，二分，三分)
    //wordModels:要在视频上显示的字幕组的模型，模型里面包含 字体、颜色 动画参数,这个参数预留，暂时填nil
    //lyricItem:要添加的歌词信息，包含某一句歌词的快照，起止显示时间、位置、大小等信息
    NSMutableArray *fontModels=@[].mutableCopy;
    for (int i=0; i<4; i++) {
        FontModel *fontModel=[FontModel new];
        
        fontModel.font=[UIFont systemFontOfSize:50];
        fontModel.fontColor=[UIColor redColor];
        
        if(i==0){
            fontModel.content=[NSString stringWithFormat:@"这是我要加的字这是我要加的字这是我要加的字 %d",i];
        }else if(i==1){
            fontModel.content=[NSString stringWithFormat:@"？？？？？？？？？？？？？？？？？？？？？ %d",i];
        }else if(i==3){
            fontModel.content=[NSString stringWithFormat:@"，，，，，，，，，，，，，，，，，，，，， %d",i];
        }else if(i==4){
            fontModel.content=[NSString stringWithFormat:@"。。。。。。。。。。。。。。。。。。。。。 %d",i];
        }
        fontModel.startTime=0*i;
        fontModel.endTime=fontModel.startTime+15.0;
        fontModel.position=CGPointMake(0, 0+60*i);//在视频中以左下角为原点的坐标 注意:这个位置坐标是笛卡尔坐标系的第一象限，与屏幕坐标系不同，注意参考之前设置的视频尺寸cameraPreset变量
        [fontModels addObject:fontModel];
        
    }
    
    NSURL *titlesVideoUrl=[[NSBundle mainBundle] URLForResource:@"titles" withExtension:@"mp4"];
    CGSize videoSize=[UIUtils getVideoSize:inPutVideoUrl];
    Float64 secondsOfTitleVideo=[UIUtils getVideoDuration:titlesVideoUrl];
    Float64 secondsOfInputVideo=[UIUtils getVideoDuration:inPutVideoUrl];
    NSLog(@"videoSize=>> %@",NSStringFromCGSize(videoSize));
    //指定遮罩的起始时间
    self.borderModel.startTime=0;
    self.borderModel.endTime=secondsOfInputVideo;
   

    [self addAnimatin:delegate.titlesModels videoSize:videoSize startTime:secondsOfTitleVideo duration:secondsOfInputVideo];
    
    [[VideoEffectUtil sharedInstance] addEffect:self.inputUrl titlesVideoUrl:nil bgMusicUrl:nil lyricItems:self.lyricLabel.lyricItems borderModel:self.borderModel fontModels:fontModels titlesModels:delegate.titlesModels cammeraTranfromModel:self.tranformModel progressBlock:^(float prog) {
        
                dispatch_async(dispatch_get_main_queue(), ^{
                    //注意在主线程更新UI
                    float percent=prog*100;
                    weakSelf.progressLabel.text=[NSString stringWithFormat:@"%.1f%%",percent];
                });
    } completeBlock:^(NSURL *url) {
                VideoPlayBackVC *videoPlayerBackVC=[[VideoPlayBackVC alloc] initWithParams:url];
                [self.navigationController pushViewController:videoPlayerBackVC animated:YES];
        
    } failureBlock:^(NSError *error) {
        
                //磁盘空间不足等会在这里报错
        
                NSLog(@"error: %@",error);
    }];

}
-(void)addAnimatin:(NSArray *)animationImageModels videoSize:(CGSize)videoSize startTime:(NSTimeInterval)startTIme duration:(NSTimeInterval)duration{
    CGPoint centerPoint=CGPointMake(videoSize.width/2, videoSize.height/2);
    
    [animationImageModels enumerateObjectsUsingBlock:^(AnimationImage * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //位置动画(必选)
        CAKeyframeAnimation *posRunAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        //设定关键帧位置，必须含起始与终止位置
        posRunAnimation.values = @[[NSValue valueWithCGPoint:CGPointMake(0, 0)],//第一个时间点的位置，这个是起始位置
                                   [NSValue valueWithCGPoint:centerPoint],//第二个时间点在屏幕中间
                                   [NSValue valueWithCGPoint:centerPoint],//第三个时间点在也屏幕中间
                                   [NSValue valueWithCGPoint:CGPointMake(videoSize.width, videoSize.height)],
                                   
                                   ];
        //设定每个关键帧的时长，如果没有显式地设置，则默认每个帧的时间=总duration/(values.count - 1)
        posRunAnimation.keyTimes = @[[NSNumber numberWithFloat:0.0],//起始时间，这个必须为0
                                     [NSNumber numberWithFloat:0.2],//第二个时间点是哪个时刻，注意这个是该时刻在整个动画期间的相对时间(0到1之间的值)，绝对时间(秒)=0.2*duration,其它的值同理，以下不在叙述
                                     [NSNumber numberWithFloat:0.5],
                                     [NSNumber numberWithFloat:0.7],
                                     ];
        posRunAnimation.repeatCount = 1;
        posRunAnimation.autoreverses = NO;
        posRunAnimation.calculationMode = kCAAnimationLinear;
        posRunAnimation.duration = duration;
        posRunAnimation.fillMode=kCAFillModeForwards;
        posRunAnimation.removedOnCompletion=NO;
        
        //形变动画(可选)，可设置 镜像、缩放、平移、等效果，这里是缩放
        CAKeyframeAnimation *transFormAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
       
        transFormAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DIdentity],
                                      [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)],
                                      [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)],
                                      [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)],
                                      ];
        
        transFormAnimation.keyTimes = @[[NSNumber numberWithFloat:0.0],
                                        [NSNumber numberWithFloat:0.2],
                                        [NSNumber numberWithFloat:0.5],
                                        [NSNumber numberWithFloat:0.7],
                                        ];
        transFormAnimation.repeatCount = 1;
        transFormAnimation.autoreverses = NO;
        transFormAnimation.calculationMode = kCAAnimationLinear;
        transFormAnimation.duration = duration;
        transFormAnimation.fillMode=kCAFillModeForwards;
        transFormAnimation.removedOnCompletion=NO;
        //透明度动画(必选)，因为视频图层的默认透明度opacty值是0，如果没有透明度动画设置在显示期间透明度值，则整个动画不会显示
        CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
        //设定关键帧位置，必须含起始与终止位置
        opacityAnimation.values = @[
                                     [NSNumber numberWithFloat:1.0f],
                                     [NSNumber numberWithFloat:1.0f],
                                     [NSNumber numberWithFloat:1.0f],
                                     [NSNumber numberWithFloat:0.0f]
                                    ];
        //设定每个关键帧的时长，如果没有显式地设置，则默认每个帧的时间=总duration/(values.count - 1)
        opacityAnimation.keyTimes = @[[NSNumber numberWithFloat:0.0],
                                        [NSNumber numberWithFloat:0.2],
                                        [NSNumber numberWithFloat:0.5],
                                        [NSNumber numberWithFloat:0.7],
                                        ];
        opacityAnimation.repeatCount = 1;
        opacityAnimation.autoreverses = NO;
        opacityAnimation.calculationMode = kCAAnimationLinear;
        opacityAnimation.duration = duration;
        opacityAnimation.fillMode=kCAFillModeForwards;
        opacityAnimation.removedOnCompletion=NO;
        //动画组
        CAAnimationGroup *animGroup = [CAAnimationGroup animation];
        animGroup.animations = [NSArray arrayWithObjects:posRunAnimation,transFormAnimation, opacityAnimation, nil];
        animGroup.duration = duration;
        animGroup.beginTime = 5.0f*idx+startTIme;
        animGroup.fillMode=kCAFillModeForwards;
        animGroup.removedOnCompletion=NO;
        obj.animation=animGroup;
        
    }];
  
}
- (IBAction)onClickNextButton:(UIButton *)sender {
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.inputUrl path]]){
        //如果还没有拍摄视频就返回
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [self saveThisCover];

    
}
-(void)saveThisCover{
    AppDelegate *delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    if(delegate.titlesModels==NULL){
        delegate.titlesModels=@[].mutableCopy;
    }
    //封面图片，这里是取的文字和图片合成后的图片
    self.animationImage.image=[UIUtils viewShot:self.titlesView];
    //这张图片在最后的视频中持续显示的时间
//    float duration=3.0f;
//    self.animationImage.duration=duration;
//    //这张图片在最后的视频中开始显示的时间
//    self.animationImage.startTime=delegate.titlesModels.count*duration;
    self.animationImage.frame=CGRectMake(100, 200, 200, 100);//跟fontModel一样，是笛卡尔坐标系的第一象限
    //所有的封面图片存在这里
    [delegate.titlesModels addObject:self.animationImage];
    
    self.animationImage=[AnimationImage new];
    [self.coverBgImage setImage:NULL];
    self.coversTitle.text=@"下一张封面的标题";
    self.titlesLabel.text=@"";

    
}
- (IBAction)onClickPickButton:(UIButton *)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    //资源类型为视频库
    
    NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    //UIImagePickerControllerSourceTypeSavedPhotosAlbum
    
    NSArray *arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType1,nil];
    
    [picker setMediaTypes: arrMediaTypes];
    
    picker.delegate = (id)self;
    
    [self.navigationController presentViewController:picker animated:YES completion:nil];
    

}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    self.inputUrl=[info objectForKey:UIImagePickerControllerMediaURL];
    self.tranformModel.isVertical=YES;
    [self dismissViewControllerAnimated:YES completion:nil];
}

//想得到相册里面的图片，请调用 UIImagePicker ，以下只演示获取视频封面
- (IBAction)selectCoverBgImage:(UIButton *)sender {
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.inputUrl path]]){
        //如果还没有拍摄视频就返回
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    //去选取图片界面
    VideoCoverPicker *picker=[VideoCoverPicker new];
    picker.inputUrl=self.inputUrl;
    [self.navigationController pushViewController:picker animated:YES];
}


-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}
-(BOOL)checkAlbumAuthorization{
    ALAuthorizationStatus author =[ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied)
    {
        //无权限
        
        return NO;
    }
    return YES;
}

@end
